package com.lanyam.travel.base.utils;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lanyam.travel.base.exception.UnloginException;

import java.io.UnsupportedEncodingException;
import java.util.Date;

public class JwtUtils {

    public static final String prop = "payload";
    public static String secret = "defaultSecret";
    public static long expireTimeInterval = 3600000L;

    public static void init(String secret, long expireTimeInterval){
        JwtUtils.secret = secret;
        JwtUtils.expireTimeInterval = expireTimeInterval;
    }

    public static void verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
        }catch (Exception e){
            throw new UnloginException();
        }

    }

    public static String getToken(String payload) {
        try {
            Date date = new Date(System.currentTimeMillis() + expireTimeInterval);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            return JWT.create()
                    .withClaim(prop, payload)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public static Date getExpireDate(){
        Date date = new Date(System.currentTimeMillis() + expireTimeInterval);
        return date;
    }

    public static Long getExpireTimeInMills(){
        return System.currentTimeMillis() + expireTimeInterval;
    }

    public static <T> T getPayload(String token, Class<T> clazz){
        DecodedJWT jwt = JWT.decode(token);
        String payload = jwt.getClaim(prop).asString();

        T t = JSONObject.parseObject(payload, clazz);
        return t;
    }
}
